<template>
  <div v-if="permissionsLists(120)">
    <!-- 头部 -->
    <page-header :title="$t('m.settingPricePlanSettings')"> </page-header>

    <div class="container">
      <div class="table_box">
        <div class="table_left">
          <div class="table_left_div">
            <span class="table_left_span">{{
              $t('m.settingPricePlan')
            }}</span>
            <img
              src="@/assets/imgs/setting/ic_add@2x.png"
              alt=""
              v-if="permissionsLists(138)"
              @click="
                params.groupIndex = groupIndex
                setPageNum(params.pageNum, params.pageSize, params)
                $router.push('/settings/price-create')
              "
            />
          </div>
          <div class="table_left_group">
            <div
              class="table_left_group_div"
              v-for="(item, index) in groupsList"
              :class="{ active1: groupIndex == index }"
              :key="item.id"
              @click="choiceIndex(index, item)"
            >
              <div :class="{ active1: groupIndex == index }">
                <eltooltip
                  :content="
                    item.isSystem ? $t('m.Default_price_plan') : item.title
                  "
                ></eltooltip>
              </div>
              <div
                v-if="!item.isSystem"
                style="align-items: center;display: flex;"
              >
                <img
                  v-if="groupIndex == index && permissionsLists(138)"
                  @click.stop="editPlan(item.id)"
                  src="@/assets/imgs/setting/ic_edit@2x.png"
                  alt=""
                  style="margin-right:8px;"
                />
                <img
                  v-if="groupIndex == index && !item.defaulted && permissionsLists(140)"
                  @click.stop="removeRule(item)"
                  src="@/assets/imgs/setting/ic_del@2x.png"
                  alt=""
                />
              </div>
            </div>
          </div>
        </div>
        <div class="table-box">
          <div class="ground_name">
            {{ $t('m.Set_up_a_price_plan') }}
          </div>
          <div class="list_div">
            <div class="page_list_div" style="padding:0 0 8px 0;">
              <el-form class="page_list_top" label-position="right">
                <el-form-item
                  :label="$t('m.search_') + ':'"
                  class="page_list_top"
                >
                  <el-input
                    prefix-icon="el-icon-search"
                    style="width:260px;"
                    clearable
                    :placeholder="
                      [
                        this.$t('m.Shop_name'),
                        this.$t('m.Shop_Details_Contact')
                      ].join(' / ')
                    "
                    v-model="params.search"
                  />
                </el-form-item>
                <el-form-item
                  :label="$t('m.Merchant_type') + ':'"
                  class="page_list_top"
                >
                  <el-select
                    v-model="params.industryId"
                    :placeholder="$t('m.pleaseChoose')"
                    ref="select1"
                    @change="searchBtn(1)"
                  >
                    <el-option
                      v-for="item in options1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item class="page_list_top page_list_search">
                  <el-button
                    class="search_button reset_button"
                    @click="searchBtn()"
                    >{{ $t('m.search_') }}</el-button
                  >
                </el-form-item>
                <el-form-item class="page_list_top page_list_search">
                  <el-button class="reset_button" @click="refreshBtn()">{{
                    $t('m.refresh')
                  }}</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="price_plan">
            <div>
              <div class="price_plan_name">
                {{
                  groupItem.isSystem
                    ? $t('m.Default_price_plan')
                    : groupItem.title
                }}
              </div>
              <div class="price_plan_rule">
                <span v-show="groupItem.freeDuration">{{
                  $t('m.billingRules1')
                    .replace(
                      '$order',
                      groupItem.freeDurationApplyOrderNum == '' ||
                        groupItem.freeDurationApplyOrderNum == null
                        ? $t('m.Every_order').toLowerCase()
                        : $t(
                            'm.' +
                              `First_order${groupItem.freeDurationApplyOrderNum}`
                          ).toLowerCase()
                    )
                    .replace('$freeDuration', groupItem.freeDuration)
                    .replace(
                      '$times1',
                      groupItem.freeDurationControlType == 1
                        ? groupItem.freeDuration > 1
                          ? $t('m.minute3')
                          : $t('m.minute2')
                        : groupItem.freeDurationControlType == 2
                        ? groupItem.freeDuration > 1
                          ? $t('m.hour4')
                          : $t('m.hour3')
                        : groupItem.freeDuration > 1
                        ? $t('m.days')
                        : $t('m.day')
                    )
                }}</span>
                <span>{{
                  $t('m.billingRules2')
                    .replace(
                      '$thereafter',
                      groupItem.freeDuration ? $t('m.thereafter') : ''
                    )
                    .replace('$currency', '')
                    .replace('$amount', $format.amountFormat(groupItem.amount))
                    .replace('$cycle', $format.numberFormat(groupItem.cycle))
                    .replace(
                      '$times2',
                      groupItem.controlType == 1
                        ? groupItem.cycle > 1
                          ? $t('m.minute3')
                          : $t('m.minute2')
                        : groupItem.controlType == 2
                        ? groupItem.cycle > 1
                          ? $t('m.hour4')
                          : $t('m.hour3')
                        : groupItem.cycle > 1
                        ? $t('m.days')
                        : $t('m.day')
                    )
                    .replace(
                      '$punctuation',
                      groupItem.dayAmount
                        ? $t('m.punctuation1')
                        : $t('m.punctuation2')
                    )
                }}</span>
                <span v-show="groupItem.dayAmount">{{
                  $t('m.billingRules3')
                    .replace('$currency', '')
                    .replace(
                      '$dayAmount',
                      $format.amountFormat(groupItem.dayAmount)
                    )
                }}</span>
                <span v-show="groupItem.amount">{{
                  $t('m.billingRules4')
                    .replace('$currency', '')
                    .replace(
                      '$penaltyAmount',
                      $format.amountFormat($cache.get('xt')['penalty-amount'])
                    )
                    .replace(
                      '$maxRentDuration',
                      $format.numberFormat(groupItem.maxRentDuration)
                    )
                    .replace(
                      '$times3',
                      groupItem.maxDurationControlType == 1
                        ? groupItem.maxRentDuration > 1
                          ? $t('m.minute3')
                          : $t('m.minute2')
                        : groupItem.maxDurationControlType == 2
                        ? groupItem.maxRentDuration > 1
                          ? $t('m.hour4')
                          : $t('m.hour3')
                        : groupItem.maxRentDuration > 1
                        ? $t('m.days')
                        : $t('m.day')
                    )
                }}</span>
              </div>
            </div>
            <el-button
              class="price_plan_button"
              :disabled="ruleList.length == 0"
              v-if="permissionsLists(141)"
              @click="ruleList.length == 0 ? '' : openChange('')"
              :style="
                ruleList.length == 0 ? 'background:#f2f5fa; opacity: 0.7;' : ''
              "
              >{{ $t('m.replacementBillingRules') }}</el-button
            >
          </div>
          <!--表格-->
          <div class="el_table_div" style="padding:0;">
            <el-table
              :data="ruleList"
              :row-key="getMerchantId"
              ref="adsId"
              @selection-change="handleSelectionChange"
            >
              <emptydata slot="empty" v-if="ruleList.length == 0" />
              <el-table-column
                type="selection"
                width="56"
                :reserve-selection="true"
                fixed="left"
              >
              </el-table-column>
              <el-table-column
                :label="$t('m.Shop_name')"
                prop="branchName"
                min-width="150"
                fixed="left"
              >
              </el-table-column>
              <el-table-column
                :label="$t('m.Merchant_type')"
                show-overflow-tooltip
                min-width="150"
              >
                <template slot-scope="scope">
                  <span>{{
                    scope.row.description
                      ? $util.langFormat(scope.row.industryName) +
                        '(' +
                        $util.langFormat(scope.row.description) +
                        ')'
                      : $util.langFormat(scope.row.industryName)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('m.Shop_Details_Contact')"
                prop="fileSize"
                show-overflow-tooltip
                min-width="150"
              >
                <template slot-scope="scope">
                  <span>{{
                    scope.row.phone | phoneFormat(scope.row.code)
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('m.bindingCabinets')"
                prop="state"
                min-width="100"
              >
                <template #default="scope">
                  <div>{{ scope.row.bindCabinetNum }}</div>
                </template>
              </el-table-column>
              <el-table-column
                :label="$t('m.Users_Details_Operation')"
                width="200"
                fixed="right"
                v-if="permissionsLists(141)"
              >
                <template #default="scope">
                  <el-button
                    type="text"
                    @click.native="openChange(scope.row)"
                    >{{ $t('m.replacementBillingRules') }}</el-button
                  ><i class="el-icon-arrow-right"></i>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 分页 -->
          <pagination
            :total="total"
            :current="params.pageNum"
            :size="params.pageSize"
            @changePageSize="handleSizeChange"
            @changePageNum="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 删除计费规则需要转移 / 更换计费规则  -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="changeDialog"
      v-if="changeDialog"
      :title="
        changeType == 1
          ? $t('m.Before_delete_price_plan')
          : $t('m.replacementBillingRules')
      "
      width="560px"
      append-to-body
      @close="closeDialog"
    >
      <div class="dialog_content">
        <div class="dialog_content1" style="padding-bottom:20px;">
          <div class="el_dialog_title1 el_dialog_title3">
            {{
              changeType == 1
                ? $t('m.Before_delete_price_plan_hint')
                : $t('m.Before_change_price_plan_hint')
            }}
          </div>
        </div>
        <div class="dialog_content1" style="padding-bottom:0;">
          <el-form
            label-position="top"
            ref="changeItem"
            :model="changeItem"
            :rules="changeRules"
          >
            <el-form-item prop="id">
              <el-select
                v-model="changeItem.id"
                style="width:100%;"
                :placeholder="$t('m.Select_Pricing_Plan')"
              >
                <el-option
                  v-for="item in options2"
                  :key="item.id"
                  :label="
                    item.isSystem ? $t('m.Default_price_plan') : item.title
                  "
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button @click="submitChange" class="cancel_btn confirm_btn">{{
          $t('m.confirm_')
        }}</el-button>
      </span>
    </el-dialog>

    <!-- 删除计费规则 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="deleteDialog"
      :title="$t('m.delete')"
      width="560px"
      append-to-body
    >
      <div class="dialog_content">
        <div class="dialog_content1">
          <div class="el_dialog_title1 el_dialog_title3">
            {{ $t('m.succeedShiftDelete2') }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialog = false" class="cancel_btn">{{
          $t('m.cancel')
        }}</el-button>
        <el-button @click="submitDelete" class="cancel_btn confirm_btn">{{
          $t('m.confirm_')
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import pagination from '@/components/pagination.vue'

export default {
  components: { pagination },
  data () {
    return {
      params: {
        pageNum: 1, //页
        pageSize: 10, //页大小
        industryId: '', //		行业id
        search: ''
      }, //搜索参数
      ruleList: [], //规则下的商家列表
      total: 0,
      options1: [{ value: '', label: this.$t('m.all') }],
      createDialog: false,
      deleteDialog: false,
      changeDialog: false,
      changeType: '',
      groupsList: [], //规则列表
      groupItem: '', //计费对象
      groupIndex: 0, //计费index
      ruleform: {
        depositAmount: '',
        id: '',
        title: ''
      }, //创建/编辑规则
      options2: [], //选择规则（当前外）
      chooseList: {
        branchId: []
      },
      changeItem: {
        id: ''
      },
      changeRules: {
        id: [
          {
            required: true,
            message: this.$t('m.Select_Pricing_Plan'),
            trigger: 'change'
          }
        ]
      },
      permissionsIds: []
    }
  },
  // computed: {
  //   penaltyAmount () {
  //     let penaltyAmount
  //     if (this.groupItem.maxDurationControlType == 2) {
  //       if (this.groupItem.controlType == 1) {
  //         penaltyAmount =
  //           (this.groupItem.amount / (this.groupItem.cycle / 60)) *
  //           this.groupItem.maxRentDuration
  //       } else if (this.groupItem.controlType == 2) {
  //         penaltyAmount =
  //           (this.groupItem.amount / this.groupItem.cycle) *
  //           this.groupItem.maxRentDuration
  //       } else {
  //         penaltyAmount =
  //           (this.groupItem.amount / (this.groupItem.cycle * 24)) *
  //           this.groupItem.maxRentDuration
  //       }
  //       return penaltyAmount
  //     } else {
  //       if (this.groupItem.controlType == 1) {
  //         penaltyAmount =
  //           (this.groupItem.amount / (this.groupItem.cycle / 60 / 24)) *
  //           this.groupItem.maxRentDuration
  //       } else if (this.groupItem.controlType == 2) {
  //         penaltyAmount =
  //           (this.groupItem.amount / (this.groupItem.cycle / 24)) *
  //           this.groupItem.maxRentDuration
  //       } else {
  //         penaltyAmount =
  //           (this.groupItem.amount / this.groupItem.cycle) *
  //           this.groupItem.maxRentDuration
  //       }
  //       return penaltyAmount
  //     }
  //   }
  // },
  created () {
    this.$store.state.permissions.forEach(item => {
      this.permissionsIds.push(Number(this.$jsencrypt.decrypt(item)))
    })
    if (!this.permissionsLists(120)) {
      return
    }
    this.params = this.$cache.get('searchParams')
      ? this.$cache.get('searchParams')
      : this.params
    this.getRuleList()
    this.getIndustriesList()
  },
  methods: {
    //权限id校验
    permissionsLists (val) {
      return this.permissionsIds.includes(val)
    },
    //编辑规则
    editPlan (id) {
      this.params.groupIndex = this.groupIndex
      this.setPageNum(this.params.pageNum, this.params.pageSize, this.params)
      this.$router.push({ path: '/settings/price-create', query: { id: id } })
    },
    // 删除规则
    removeRule (items) {
      this.ruleform = items
      if (this.ruleList.length == 0) {
        this.deleteDialog = true
      } else {
        this.options2 = this.groupsList.filter(
          item => item.id != this.ruleform.id
        )
        this.changeItem.id = ''
        this.changeDialog = true
        this.changeType = 1
      }
    },

    //确认删除
    submitDelete () {
      this.$api.billing.remove(this.ruleform).then(res => {
        if (this.$ok(res)) {
          this.$message.success(res.message)
          this.deleteDialog = false
          this.clearTable()
          this.remPageNum()
          this.getRuleList()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //关闭弹窗
    closeDialog () {
      this.changeDialog = false
      if (this.changeType == 3) {
        this.clearTable()
      }
    },
    //转移/更换计费规则
    submitChange () {
      this.$refs.changeItem.validate(valid => {
        if (!valid) {
          return
        }
        if (this.changeType == 1) {
          const params = {
            //计费规则id
            billingId: this.ruleform.id,
            //新计费规则id
            newBillingId: this.changeItem.id
          }
          this.$api.billing.modifyAllBranchRule(params).then(res => {
            if (this.$ok(res)) {
              this.$message.success(res.message)
              this.changeDialog = false
              this.getPage()
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          this.$api.billing
            .batchModifyBranchRule({
              billingId: this.changeItem.id,
              branchId: this.chooseList.branchId
            })
            .then(res => {
              if (this.$ok(res)) {
                this.$message.success(res.message)
                this.changeDialog = false
                this.getPage()
                this.clearTable()
              } else {
                this.$message.error(res.message)
              }
            })
        }
      })
    },
    //打开更换弹窗
    openChange (item) {
      if (item) {
        this.clearTable()
        this.chooseList.branchId = [item.branchId]
        this.changeType = 3
      } else {
        this.changeType = 2
      }
      if (this.chooseList.branchId.length == 0) {
        this.$message.error(this.$t('m.Select_merchant'))
        return
      }
      this.options2 = this.groupsList.filter(
        item => item.id != this.groupItem.id
      )
      this.changeItem.id = ''
      this.changeDialog = true
    },

    //预付款列表
    getRuleList () {
      this.$api.billing.getBillingList().then(res => {
        if (this.$ok(res)) {
          this.groupsList = res.data
          this.groupIndex = this.params.groupIndex ? this.params.groupIndex : 0
          this.groupItem = res.data[0]
          if (this.groupsList.length > 0) {
            this.groupItem = this.params.groupIndex
              ? this.groupsList[this.params.groupIndex]
              : this.groupsList[0]

            this.getPage()
          }
        }
      })
    },

    // 获取预付款规则下的商家列表
    getPage () {
      this.$api.billing
        .getBillingShopList(this.groupItem.id, this.params)
        .then(res => {
          if (this.$ok(res)) {
            this.ruleList = res.data.records
            this.total = res.data.total
          }
        })
    },
    //切换页大小
    handleSizeChange (val) {
      this.params.pageSize = val
      this.getPage()
    },
    //切换页
    handleCurrentChange (val) {
      this.params.pageNum = val
      this.getPage()
    },
    //搜索
    searchBtn (e) {
      this.params.pageNum = 1
      this.$nextTick(() => {
        e ? this.$refs[`select${e}`].blur() : ''
      })
      this.remPageNum()
      this.clearTable()
      this.getPage()
    },
    //重置
    refreshBtn () {
      this.params = this.$options.data.call(this).params
      this.remPageNum()
      this.clearTable()
      this.getPage()
    },
    // 商家id
    getMerchantId (row) {
      return row.branchId
    },

    // 选中的行
    handleSelectionChange (e) {
      this.chooseList.branchId = e.map(item => item.branchId)
      // console.log(this.chooseList.branchId)
    },
    // 清空选中的行
    clearTable () {
      this.chooseList = this.$options.data.call(this).chooseList
      this.$refs.adsId.clearSelection()
    },
    //选择
    choiceIndex (index, item) {
      this.groupIndex = index
      this.groupItem = item
      this.params = this.$options.data.call(this).params
      this.ruleList = []
      this.total = 0
      this.clearTable()
      this.getPage()
    },
    //获取行业列表
    getIndustriesList () {
      this.$api.common.getIndustriesList().then(res => {
        if (this.$ok(res)) {
          res.data.map(item => {
            this.options1.push({
              value: item.id,
              label: item.description
                ? this.$util.langFormat(item.industryName) +
                  '(' +
                  this.$util.langFormat(item.description) +
                  ')'
                : this.$util.langFormat(item.industryName)
            })
          })
        }
      })
    }
  }
}
</script>
<style scoped lang="scss">
.table_box {
  min-width: 1092px;
  display: flex;
  background: #ffffff;
  border-radius: 10px;
  .table-box {
    min-width: 872px;
    flex: 1;
    padding: 20px;
    .ground_name {
      font-size: 16px;
      font-weight: 600;
      text-align: left;
      color: #39404d;
      line-height: 22px;
      margin-bottom: 20px;
    }
  }
  .table_left {
    width: 256px;
    min-width: 256px;
    border-right: 1px solid #ececee;
    .table_left_div {
      padding: 20px 12px 20px 20px;
      border-bottom: 1px solid #ececee;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .table_left_span {
        font-size: 16px;
        font-weight: 600;
        text-align: left;
        color: #39404d;
        line-height: 22px;
      }
      img {
        width: 16px;
        height: 16px;
        cursor: pointer;
      }
    }
    .table_left_group {
      width: 255px;
      min-width: 255px;
      .table_left_group_div {
        padding: 12px 12px 12px 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        cursor: pointer;
        div {
          width: 180px !important;
          font-size: 14px;
          font-weight: 500;
          text-align: left;
          color: #39404d;
          line-height: 16px;
          margin-right: 4px;
        }

        img {
          width: 16px;
          height: 16px;
          cursor: pointer;
        }
      }
      .table_left_group_div:hover {
        background: #f2f5fa;
        color: var(--text-color) !important;
        div {
          background: #f2f5fa;
          color: var(--text-color) !important;
        }
      }
      .active1 {
        background: #f2f5fa;
        color: var(--text-color) !important;
        ::v-deep .el-tooltip {
          color: var(--text-color) !important;
        }
      }
    }
  }
  .price_plan {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    .price_plan_name {
      font-size: 14px;
      font-weight: 500;
      text-align: left;
      color: #39404d;
      line-height: 16px;
      margin-bottom: 6px;
    }
    .price_plan_rule {
      font-size: 12px;
      font-weight: 400;
      text-align: left;
      color: #646b80;
      line-height: 14px;
    }
    .price_plan_button {
      border: 1px solid #d2d8e2;
      background-color: #ffffff;
      color: var(--text-color);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 14px;
      padding: 10px 20px;
      height: 36px;
      font-weight: 500;
      line-height: 36px;
      margin-left: 50px;
      margin-top: 7px;
    }
  }
}
.el-icon-arrow-right {
  color: var(--text-color);
}
</style>
